package com.cmyshare.design.strategyAndFactorySpring;

import java.math.BigDecimal;

/**
 * @version 1.0
 * @Author cmy
 * @Date 2025/10/13 16:21
 * @desc 支付服务类（策略使用者） 支付服务类，封装支付流程，对外提供统一支付接口
 */
@Service
public class PaymentService {

    @Autowired
    private PaymentFactory paymentFactory;

    /**
     * 处理支付
     * @param paymentType 支付类型
     * @param request 支付请求参数
     * @return 支付结果
     */
    public PaymentResult processPayment(String paymentType, PaymentRequest request) {
        // 1. 参数校验
        validatePaymentRequest(request);

        // 2. 获取支付策略
        PaymentStrategy strategy = paymentFactory.getPaymentStrategy(paymentType);

        // 3. 执行支付
        return strategy.pay(request);
    }

    /**
     * 验证支付请求参数
     */
    private void validatePaymentRequest(PaymentRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("支付请求不能为空");
        }
        if (request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("支付金额必须大于0");
        }
        if (request.getOrderId() == null || request.getOrderId().trim().isEmpty()) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
    }
}
